var lrdCorp = {
    baseUrl: "/corp",
    entity: "lrdCorp",
    tableId: "lrdCorpTable",
    toolbarId: "toolbar",
    currentItem: {},
};
lrdCorp.columns = function () {
    return [
        {
            field: 'selectItem',
            radio: true
        },{  
            title: '序号',
            formatter: function (value, row, index) {  
                return index+1;
            }  
        }, {
            field: 'corpCd',
            title: '法人号'
        }, {
            field: 'corpName',
            title: '法人名称'
        }, {
            field: 'host',
            title: '访问地址'
        }, {
            field: 'corpFlag',
            title: '状态',
            formatter:function (value, row, index) {
                var result=''
                if(value==0){
                    result='正常';
                }else {
                    result='停用';
                }
                return result;
            }
        },{
            field: 'corpBelong',
            title: 'logo名称',           
        }];
};
//得到查询的参数
lrdCorp.queryParams = function (params) {
	if (!params)
        return {
            corpCd:$("#corpCd").val()
        };
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        limit: params.limit, //页面大小
        page: params.offset/params.limit+1, //页码
        corpCd:$("#corpCd").val()
    };
    return temp;
};
lrdCorp.responseHandler = function(response){
	if(response.code =='200'){
		return response.data;
	}
	return false;
};
lrdCorp.init = function () {
    lrdCorp.table = $('#' + lrdCorp.tableId).bootstrapTable({
        url: lrdCorp.baseUrl+'/page', //请求后台的URL（*）
    	method: 'get', //请求方式（*）
    	toolbar: '#' + lrdCorp.toolbarId, //工具按钮用哪个容器
    	cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 10, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        showColumns: false, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        clickToSelect: true, 
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        singleSelect:true,
        striped:true,
        queryParams: lrdCorp.queryParams,//传递参数（*）
        responseHandler:lrdCorp.responseHandler,
        columns: lrdCorp.columns()
    });
};
lrdCorp.select = function (layerTips) {
    var rows = lrdCorp.table.bootstrapTable('getSelections');
    if (rows.length == 1) {
        lrdCorp.currentItem = rows[0];
        return true;
    } else {
        layerTips.msg("请选中一行");
        return false;
    }
};
lrdCorp.refresh = function () {
    lrdCorp.table.bootstrapTable('refresh', lrdCorp.queryParams());
};


layui.use(['form', 'layedit', 'laydate', 'element'], function () {
    lrdCorp.init();
    var editIndex;
    //var layerTips = parent.layer === undefined ? layui.layer : parent.layer, //获取父窗口的layer对象
    var layerTips = layui.layer;
        layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;  
    //初始化页面上面的按钮事件
    $('#btn_query').on('click', function () {
        lrdCorp.table.bootstrapTable('refresh', lrdCorp.queryParams());
    });
    $('#btn_add').on('click', function () {
    	var corpCd=lrdCorp.corpCd;
        //本表单通过ajax加载 --以模板的形式，当然你也可以直接写在页面上读取
        $.get(lrdCorp.entity + '/edit', null, function (form) {
            addBoxIndex = layer.open({
                type: 1,
                title: '添加法人信息',
                content: form,
                id:'corp_add',
                btn: ['保存', '取消'],
                shade: [0.3, '#393D49'],
                shadeClose: true,
                offset: ['20px', '10%'],
                area: ['80%', '80%'],
                maxmin: true,
                yes: function (index) {
                    layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=edit]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                    var form = layui.form;
                     editIndex =layedit.build('description_editor',{
                   	 tool: [  'strong' //加粗
                	          ,'italic' //斜体
                	          ,'underline' //下划线
                	          ,'del' //删除线
                	          ,'|' //分割线
                	          ,'left' //左对齐
                	          ,'center' //居中对齐
                	          ,'right' //右对齐
                	       ]
                    });
                    var json = {
                        "corpFlag":"YesNo",
                    }
                    selectOnload({
                        "json": json,
                        "isDefault": false,
                        "func": form.render,//渲染表单
                        "length": 1,
                    });
                    form.on('submit(edit)', function (data) {
                        $.ajax({
                            url: lrdCorp.baseUrl+"/add",
                            type: 'post',
                            data: JSON.stringify(data.field),
                            dataType: "json",
                            contentType:"application/json",
                            success: function (data) {
                            	if(data.code=='200'){
	                                layerTips.msg('添加成功');
	                                layerTips.close(index);
	                                lrdCorp.refresh();
                            	}else{
                            		layerTips.msg(data.message);
	                                layerTips.close(index);
                            	}
                            }

                        });
                        //这里可以写ajax方法提交表单
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
                end: function () {
                    addBoxIndex = -1;
                }
            });
        });
    });
    $('#btn_edit').on('click', function () {
        if (lrdCorp.select(layerTips)) {
        	var result= lrdCorp.currentItem;
            $.get(lrdCorp.entity + '/edit', null, function (form) {
                layer.open({
                    type: 1,
                    title: '编辑法人信息',
                    id:'corp_edit',
                    content: form,
                    btn: ['保存', '取消'],
                    shade: [0.3, '#393D49'],
                    shadeClose: true,
                    offset: ['20px', '10%'],
                    area: ['80%', '80%'],
                    maxmin: true,
                    yes: function (index) {
                        layedit.sync(editIndex);
                        //触发表单的提交事件
                        $('form.layui-form').find('button[lay-filter=edit]').click();
                    },
                    full: function (elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function () {
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function (layero, index) {
                        var form = layui.form;
                        var renderForm=function(){	   
                        	layero.find("select[name='corpFlag']").val(result['corpFlag']);
                        	form.render();
                        }
                        $('input[name=corpCd]').attr("readonly","readonly");
                        $("input[name=corpCd]").css("background-color","#D3D3D3");
                        layero.find('#description_editor').val(result.corpDesc);
                        setFromValues(layero, result);//表单赋值
                        editIndex =layedit.build('description_editor',{
	                       	tool: [  'strong' //加粗
	                    	          ,'italic' //斜体
	                    	          ,'underline' //下划线
	                    	          ,'del' //删除线
	                    	          ,'|' //分割线
	                    	          ,'left' //左对齐
	                    	          ,'center' //居中对齐
	                    	          ,'right' //右对齐
	                    	       ]
	                    });
                       // form.render();
                        var json = {
                            "corpFlag": "SYS_ORG_FLAG",
                        }
                        selectOnload({
                            "json": json,
                            "isDefault": false,
                            "func": renderForm,//渲染表单
                            "length": 1,
                        });
                        
                        form.on('submit(edit)', function (data) {                     	
                            $.ajax({
                                url: lrdCorp.baseUrl+'/update',
                                type: 'put',
                                data: JSON.stringify(data.field),
                                dataType: "json",
                                contentType:"application/json",
                                success: function (data) {
                                	if(data.code=='200'){
                                		layerTips.msg('更新成功');
	                                    layerTips.close(index);
	                                    lrdCorp.refresh();
	                                }else {
	                                    layerTips.msg(data.message);
	                                    layerTips.close(index);
	                                }
                            	}

                            });
                            //这里可以写ajax方法提交表单
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });
                    }
                });
            });
        }
    });
    //logo上传
    $('#btn_upload').on('click', function () {
        if (lrdCorp.select(layerTips)) {
        	var item= lrdCorp.currentItem;
            $.get(lrdCorp.entity + '/upload', null, function (form) {
                layer.open({
                    type: 1,
                    title: 'logo上传',
                    id:'corp_logo',
                    content: form,
                    btn: ['关闭'],
                    shade: [0.3, '#393D49'],
                    shadeClose: true,
                    offset: ['20px', '10%'],
                    area: ['70%', '70%'],
                    maxmin: true,
                    yes: function (index) {
                    	layerTips.close(index);
                    },
                    full: function (elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function () {
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function (layero, index) {
                    	if(item.logo1!=null&&item.logo1!=''){
                    		layero.find("#demo1").attr('src', "/sysFile/getPic/"+item.logo1);
                    	}
                    	if(item.logo2!=null&&item.logo2!=''){
                    		layero.find("#demo2").attr('src', "/sysFile/getPic/"+item.logo2);
                    	}
                    	if(item.logo3!=null&&item.logo3!=''){
                    		layero.find("#demo3").attr('src', "/sysFile/getPic/"+item.logo3);
                    	}
                    	var updateCorp=function(logo,res){
                    		if(item[logo]==null||item[logo]==""){
            		    		var data=res.data;
            		    		item[logo]=data.id;
            		    		$.ajax({
                                    url: lrdCorp.baseUrl+'/update',
                                    type: 'put',
                                    data: JSON.stringify(item),
                                    dataType: "json",
                                    contentType:"application/json",
                                    success: function (data) {
                                    	if(data.code=='200'){    	                                    		
                                    		layerTips.msg('上传成功');  
    	                                }else {
    	                                	item[logo]="";
    	                                    layerTips.msg(data.message);
    	                                }
                                	}

                                });
            		    	}else{
            		    		layerTips.msg('上传成功'); 
            		    	}
                    	}
                    	layui.use('upload', function(){
                    		  var $ = layui.jquery,
                    		  upload = layui.upload;
                    		  var uploadRender=function(elem){
                    			  upload.render({
                          		    elem: '#'+elem
                          		    ,url: '/sysFile/upload/' 
                          		    ,data:{"id":item[elem]==null?"":item[elem],"refId":item.corpCd,"name":elem}	
                          		   	,before: function(obj){
                          		   	     //预读本地文件示例，不支持ie8
                          		   	     obj.preview(function(index, file, result){
                          		   	       $('#demo1').attr('src', result); //图片链接（base64）
                          		   	     });
                          	   	    }
                          		    ,done: function(res){
                          		    	updateCorp(elem,res);	                		    	
                          		    }
                          		    ,error: function(){
                          		        //演示失败状态，并实现重传
                          		        var demoText = $('#demoText1');
                          		        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                          		        demoText.find('.demo-reload').on('click', function(){
                          		          uploadInst.upload();
                          		        });
                          		      }
                          		  });
                    		  }
                    		  uploadRender('logo1');
                    		  uploadRender('logo2');
                    		  uploadRender('logo3');
                    		                 		 
                    	});
                    }
                });
            });
        }
    });
    $('#btn_del').on('click', function () {
        if (lrdCorp.select(layerTips)) {       	
            layer.confirm('确定删除数据吗？', null, function (index) {
                $.ajax({
                    url: lrdCorp.baseUrl+"/delete",
                    type: "DELETE",
                    contentType:"application/json",
                    data: JSON.stringify(lrdCorp.currentItem),
                    success: function (data) {
                        if (data.code == '200') {
                            layerTips.msg("移除成功！");
                            lrdCorp.refresh();
                        } else {
                            layerTips.msg(data.message);
                        }
                    }
                });
                layer.close(index);
            });
        }
    });
    
});

